package com.power.sifa.util;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.symmetric.SM4;

import javax.crypto.SecretKey;

/**
 * @ClassName SM2EncryptUtil
 * @Author xiongzw
 * @Date 2024/1/24 14:29
 * @Description 国密SM4生成密钥key,前后端使用的秘钥保持一致
 * @Version: 1.0
 **/

public class SM4EncryptUtil {


    public static void main(String[] args) {
        /**
         * 生成公私钥
         */
        SM4 sm4 = new SM4();
        SecretKey secretKey = sm4.getSecretKey();
        byte[] encoded = secretKey.getEncoded();
        // 生成密钥
        String encodeHexStr = HexUtil.encodeHexStr(encoded);
        System.out.println("密钥:" + encodeHexStr);

        // 加密
        String demo = "3604011996083192011";
        String encode = sm4.encryptHex(demo);
        System.out.println("加密:" + encode);
        // 解密
        SM4 newSm4 = new SM4(HexUtil.decodeHex(encodeHexStr));
        String decryptStr = newSm4.decryptStr(encode,  CharsetUtil.CHARSET_UTF_8);
        System.out.println("解密:" + decryptStr);

    }

}
